<?php

namespace App\Observers;

use App\Models\Repository;
use Illuminate\Database\Eloquent\Model;

class RepositoryObserver
{

    public function creating(Repository $repository)
    {
        $repository->user_id = auth()->id();
    }

    /**
     * Handle the repository "updated" event.
     *
     * @param  \App\Models\Repository $repository
     * @return void
     */
    public function updated(Repository $repository)
    {
        Model::unsetEventDispatcher();
        $repository->timestamps = false;
        $sum = $repository->currentChapters()->pluck('content')->sum(function ($content) {
            return mb_strlen($content);
        });

        $repository->length = $sum + mb_strlen($repository->content);
        $repository->save();
    }

    /**
     * Handle the repository "deleted" event.
     *
     * @param  \App\Models\Repository $repository
     * @return void
     */
    public function deleted(Repository $repository)
    {
        //
    }

    /**
     * Handle the repository "restored" event.
     *
     * @param  \App\Models\Repository $repository
     * @return void
     */
    public function restored(Repository $repository)
    {
        //
    }

    /**
     * Handle the repository "force deleted" event.
     *
     * @param  \App\Models\Repository $repository
     * @return void
     */
    public function forceDeleted(Repository $repository)
    {
        //
    }
}
